package com.campus.service.impl;

import com.campus.dao.TeacherDao;
import com.campus.dao.UserDao;
import com.campus.model.Teacher;
import com.campus.service.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author HLQ
 * @date 2024/11/19 9:50
 */
@Slf4j
@Service
public class TeacherServiceImpl implements TeacherService {
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    UserDao userDao;
    @Autowired
    JdbcTemplate jdbcTemplate;

    @Transactional
    @Override
    public int addTeacher(Teacher teacher) {
        // 检查学生的login_id是否存在于 t_sys_user 表的 id 中
        String sql1 = "SELECT COUNT(1) FROM t_sys_user WHERE id = ?";
        int userCount = jdbcTemplate.queryForObject(sql1, Integer.class, teacher.getLoginId());

        // 如果用户未注册
        if (userCount == 0) {
            log.error("用户未注册");
            return 0;
        }

        // 检查学生的login_id是否存在于 t_sys_user_role 表的 user_id 中
        String sql2 = "SELECT COUNT(1) FROM t_sys_user_role WHERE user_id = ?";
        int roleCount = jdbcTemplate.queryForObject(sql2, Integer.class, teacher.getLoginId());

        // 如果用户未分配角色
        if (roleCount == 0) {
            log.error("用户未分配角色");
            return 0;
        }

        // 检查角色是否为2（教师角色）
        String sql3 = "SELECT role_id FROM t_sys_user_role WHERE user_id = ?";
        Integer roleId = jdbcTemplate.queryForObject(sql3, Integer.class, teacher.getLoginId());

        // 如果角色不是教师（假设角色 ID 2 对应教师角色）
        if (roleId == null || roleId != 2) {
            log.error("用户角色不是教师");
            return 0;
        }
        return teacherDao.addTeacher(teacher);
    }
    @Override
    public Teacher queryTeacherById(int id){
        return teacherDao.queryTeacherById(id);
    }

}
